<template>
  <div class="app-container" v-loading="loading">
    <el-dialog :title="prop.title" :visible.sync="prop.open" width="680px" :close-on-click-modal="false" :show-close="false" destroy-on-close append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位类型">
              <el-input v-model="form.parentName" disabled style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位名称" prop="postName">
              <el-input v-model="form.postName" placeholder="请输入岗位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位编码" prop="postCode">
              <el-input v-model="form.postCode" placeholder="请输入岗位编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="适用组织" prop="postOrganizations">
              <Treeselect
                v-model="form.postOrganizations"
                :multiple="true"
                :options="organizationData"
                :flat="true"
                :normalizer="normalizer"
                placeholder="请选择适用组织"
                noOptionsText="无数据">
              </Treeselect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="适用职级" prop="postGrades">
              <el-select v-model="form.postGrades" style="width: 100%;" :multiple="true">
                <el-option
                  v-for="item in postGradeData"
                  :key="item.gradeId"
                  :label="item.gradeName"
                  :value="item.gradeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位说明">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入岗位说明"
                v-model="form.postDescript">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入备注"
                v-model="form.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="saveLoading">确 定</el-button>
        <el-button @click="cancel({isSaveData:false})">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {add,edit,getDetail,checkNameIsUnique,checkCodeIsUnique} from '@/api/organization/post/post.js'
  import {getGradeSelectItemsByPost} from '@/api/organization/grade/grade.js'
  import {getOrganizationsSelectItems} from '@/api/organization/organization/organization.js'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  export default {
    name: "PostEdit",
    dicts: [],
    components: { Treeselect },
    props:{
      prop:{
        type:Object,
        default:function(){
          return {
            open:false,
            title:'新增',
            parentId:null,
            parentName:null,
            parentSysCode:null,
            editId:null
          }
        }
      }
    },
    data() {
      var nameValidator = (rule, value, callback) => {
        if(value!==null&&value.trim()!==""){
          checkNameIsUnique({postName:value,postId:this.form.postId}).then(res =>{
            let isUnique = res.data
            if (isUnique) {
              return callback()
            }else{
              return callback(new Error('岗位名称不能重复'));
            }
          })
        }else{
           return callback(new Error('岗位名称不能为空'));
        }
      };
      var codeValidator = (rule, value, callback) => {
        if(value!==null&&value.trim()!==""){
          checkCodeIsUnique({postCode:value,postId:this.form.postId}).then(res =>{
            let isUnique = res.data
            if (isUnique) {
              return callback()
            }else{
              return callback(new Error('岗位编码不能重复'));
            }
          })
        }else{
           return callback(new Error('岗位编码不能为空'));
        }
      };
      return {
        saveLoading:false,
        loading:false,
        isEdit:false,
        isLoadData:false,
        organizationData: [],
        postGradeData:[],
        // 表单参数
        form: {
          postParentId:null,
          parentName:null,
          postName:null,
          postCode:null,
          postOrganizations:null,
          postGrades:null,
          postType:'1',
          isEnable:'1',
        },
        // 表单校验
        rules: {
          postName: [
            { required: true, validator:nameValidator, trigger: "blur" }
          ],
          postCode: [
            { required: true, validator:codeValidator, trigger: "blur" }
          ],
          postOrganizations: [
            { required: true, message: "请选择岗位适用组织机构", trigger: "blur" }
          ],
          postGrades: [
            { required: true, message: "请选择岗位适用职级", trigger: "blur" }
          ]
        }
      };
    },
    methods: {
      normalizer(node) {
        return {
          id: node.organizationSysCode,
          label: node.organizationName,
          children: node.children,
        }
      },
      //加载编辑时需要的前置数据
      getPreData(){
        //修改时加载详情数据
        if(this.prop.editId!==null){
          this.isEdit = true
          this.getDetail()
        }
        //设置分类名称
        this.form.parentName = this.prop.parentName
        this.form.postParentId = this.prop.parentId
        this.getOrganizationDatas()
        this.getGradeDataOfPost()
      },
      getOrganizationDatas(){
        getOrganizationsSelectItems().then(res =>{
          let organizationData = res.data
          this.organizationData = this.handleTree(organizationData, "organizationId","organizationParentId");
        }).catch(err =>{
          console.log('查询组织机构数据错误，原因：',err)
        })
      },
      getGradeDataOfPost(){
        getGradeSelectItemsByPost({postSysCode:this.prop.parentSysCode}).then(res =>{
          this.postGradeData = res.data
        }).catch(err =>{
          console.log('查询岗位类型关联职级数据错误，原因：',err)
        })
      },
      getDetail(){
        getDetail({postId:this.prop.editId}).then(res =>{
          let {postGrades,postOrganizations,...post} = res.data
          post.postGrades = postGrades.map(gra => gra.gradeId)
          post.postOrganizations = postOrganizations.map(po =>po.organizationSysCode)
          let formData = this.form
          this.form = {...formData,...post}
        }).catch(err =>{
          console.log('查询岗位详情数据错误，原因：',err)
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.saveLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            let formData = this.setFormData()
            if (this.isEdit) {
              edit(formData).then(response => {
                this.saveLoading = false
                this.$modal.msgSuccess("修改成功");
                this.cancel({isSaveData:true})
              }).catch(err =>{
                console.log('保存失败，原因：',err)
                this.saveLoading = false
              });
            } else {
              add(formData).then(response => {
                this.saveLoading = false
                this.$modal.msgSuccess("新增成功");
                this.cancel({isSaveData:true})
              }).catch(err =>{
                console.log('保存失败，原因：',err)
                this.saveLoading = false
              });
            }
          }else{
            this.saveLoading = false
          }
        });
      },
      setFormData(){
        let {postOrganizations,postGrades,...formData} = this.form
        //处理岗位适用组织机构数据
        let postOrgs = postOrganizations.map(orgSysCode =>{
          return {organizationSysCode:orgSysCode,postSysCode:null,isEnable:'1'}
        })
        //处理岗位适用职级数据
        let postGras = postGrades.map(id =>{
          return {postSysCode:null,gradeId:id}
        })
        return {post:formData,postGrades:postGras,postOrganizations:postOrgs}
      },
      // 表单重置
      reset() {
        this.form = {
          postParentId:null,
          parentName:null,
          postName:null,
          postCode:null,
          postOrganizations:null,
          postgradeDatas:null,
          postType:'1',
          isEnable:'1',
        };
        this.isEdit = false
      },
      // 取消按钮
      cancel(closeParam) {
        this.reset()
        this.$emit('close',closeParam)
      },
    },
    mounted() {
      this.getPreData()
    },
  };
</script>
<style scoped>

</style>
